package graphics.screens;

import graphics.BootColor;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;

import tool.KeyCode;
import tool.Log;
import tool.ScreenUtils;
import boot.Boot;

public class AlertScreen extends Canvas implements CommandListener {

	private final Command okCommand = new Command("OK", Command.OK, 1);
	private final Command logCommand = new Command("logs", Command.CANCEL, 1);
	private String message;
	private String title;
	private int hOffset = 0;

	public AlertScreen(String aMessage, String aTitle) {
		message = aMessage;
		title = aTitle;
		addCommand(okCommand);
		addCommand(logCommand);
		setCommandListener(this);
	}

	protected void paint(Graphics g) {
		ScreenUtils.setBlackBackground(g);
		g.setColor(BootColor.BASIC_MENU_COLOR);
		g.drawString(title, 0, 0, Graphics.LEFT | Graphics.TOP);

		g.setColor(BootColor.WHITE);
		int fHeight = g.getFont().getHeight();
		String remaining = message;
		int lineIndex = 0;

		while (remaining.length() > 1) {
			int index = remaining.indexOf("\n");
			String line = null;
			
			if (index > -1) {				
				line = remaining.substring(0, index);
				remaining = remaining.substring(index + 1);
			} else {
				line = remaining;
				remaining = "";
			}
			
			g.drawString(line, 10 - 120 * hOffset , fHeight
					* (lineIndex + 1), Graphics.LEFT | Graphics.TOP);
			lineIndex++;
		}

		g.drawString(remaining, 0, fHeight * (lineIndex + 1), Graphics.LEFT
				| Graphics.TOP);
	}

	public void commandAction(Command command, Displayable dis) {
		if (command == okCommand) {
			Boot.displayGetBackScreen();
		} else if (command == logCommand) {
			Log.display();
		}
	}

	public void keyPressed(int keyCode) {
		if (keyCode == KeyCode.GAUCHE) {
			if (hOffset > 0) {
				hOffset--;
				repaint();
			}
		} else if (keyCode == KeyCode.DROITE) {
			hOffset++;
			repaint();
		}
	}
}
